<template>
  <div class="container">
    <a-card class="general-card" title="查询表格">
      <a-row>
        <a-col :flex="1">
          <a-form
            ref="searchForm"
            :model="searchParams"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="id" label="用户编号">
                  <a-input
                    v-model="searchParams.id"
                    placeholder="请输入用户编号"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="userName" label="用户昵称">
                  <a-input
                    v-model="searchParams.userName"
                    placeholder="请输入用户昵称"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="userProfile" label="简介">
                  <a-input
                    v-model="searchParams.userProfile"
                    placeholder="请输入简介"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="userRole" label="用户角色">
                  <a-select
                    v-model="searchParams.userRole"
                    placeholder="请选择用户角色"
                    allow-clear
                  >
                    <a-option value="admin">管理员</a-option>
                    <a-option value="user">用户</a-option>
                    <a-option value="ban">封号</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="$refs.searchForm.resetFields()">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="addVisible = true">
              <template #icon>
                <icon-plus />
              </template>
              新增
            </a-button>
            <a-upload action="/">
              <template #upload-button>
                <a-button> 批量导入</a-button>
              </template>
            </a-upload>
            <a-modal
              v-model:visible="addVisible"
              title="用户信息"
              @cancel="$refs.addForm.resetFields()"
              @before-ok="doInsert"
            >
              <a-form :model="addData" :rules="rules" ref="addForm">
                <a-form-item
                  field="userAccount"
                  label="用户账号"
                  validate-trigger="blur"
                >
                  <a-input v-model="addData.userAccount" />
                </a-form-item>
                <a-form-item field="userName" label="用户昵称">
                  <a-input v-model="addData.userName" />
                </a-form-item>
                <a-form-item field="userAvatar" label="用户头像">
                  <a-upload action="/">
                    <template #upload-button>
                      <a-avatar :size="60" class="info-avatar">
                        <template #trigger-icon>
                          <icon-camera />
                        </template>
                        <!--                        <img v-if="fileList.length" :src="fileList[0].url" />-->
                      </a-avatar>
                    </template>
                  </a-upload>
                </a-form-item>

                <a-form-item field="userRole" label="用户角色">
                  <a-select v-model="addData.userRole">
                    <a-option value="admin">管理员</a-option>
                    <a-option value="user">用户</a-option>
                    <a-option value="ban">封号</a-option>
                  </a-select>
                </a-form-item>
              </a-form>
            </a-modal>
          </a-space>
        </a-col>
        <a-col
          :span="12"
          style="display: flex; align-items: center; justify-content: end"
        >
          <a-button>
            <template #icon>
              <icon-download />
            </template>
            下载
          </a-button>
          <a-tooltip content="刷新">
            <div class="action-icon" @click="search">
              <icon-refresh size="18" />
            </div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip content="密度">
              <div class="action-icon">
                <icon-line-height size="18" />
              </div>
            </a-tooltip>
            <template #content>
              <a-doption
                v-for="item in densityList"
                :key="item.value"
                :value="item.value"
                :class="{ active: item.value === size }"
              >
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
        </a-col>
      </a-row>
      <a-table
        :columns="columns"
        :data="dataList"
        :size="size"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
        }"
        @page-change="onPageChange"
      >
        <template #userAvatar="{ record }">
          <a-avatar :imageUrl="record.userAvatar" />
          <!--        {{ record.userAvatar }}   <a-badge status="danger" text="Danger" />-->
        </template>
        <template #userProfile="{ record }">
          <a-popover title="用户简介" trigger="click">
            <a-button size="mini" type="text">查看简介</a-button>
            <template #content>
              <p>{{ record.userProfile ? record.userProfile : '暂无' }}</p>
            </template>
          </a-popover>
        </template>
        <template #userRole="{ record }">
          <a-badge
            :status="
              record.userRole === 'admin'
                ? 'danger'
                : record.userRole === 'user'
                ? 'success'
                : 'normal'
            "
            :text="record.userRole"
          />
        </template>
        <template #createTime="{ record }">
          {{ moment(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template #optional="{ record }">
          <a-space>
            <a-button type="primary" @click="handleClick(record)">
              修改
            </a-button>
            <a-modal
              v-model:visible="visible"
              title="用户信息"
              @cancel="handleCancel"
              @before-ok="doUpdate"
              :mask="true"
            >
              <a-form :model="formData" ref="updateForm">
                <a-form-item field="userAvatar" label="用户头像">
                  <a-upload action="/">
                    <template #upload-button>
                      <a-avatar :size="60" class="info-avatar">
                        <template #trigger-icon>
                          <icon-camera />
                        </template>
                        <img
                          :src="formData.userAvatar"
                          style="border-radius: 50%"
                        />
                      </a-avatar>
                    </template>
                  </a-upload>
                </a-form-item>
                <a-form-item field="id" label="id">
                  <a-input v-model="formData.id" disabled readonly />
                </a-form-item>
                <a-form-item field="userName" label="用户昵称">
                  <a-input v-model="formData.userName" />
                </a-form-item>

                <a-form-item field="userAvatar" label="用户头像">
                  <a-input v-model="formData.userAvatar" />
                </a-form-item>
                <a-form-item field="userProfile" label="用户简介">
                  <a-textarea v-model="formData.userProfile" />
                </a-form-item>
                <a-form-item field="userRole" label="用户角色">
                  <a-select v-model="formData.userRole">
                    <a-option value="admin">管理员</a-option>
                    <a-option value="user">用户</a-option>
                    <a-option value="ban">封号</a-option>
                  </a-select>
                </a-form-item>
              </a-form>
            </a-modal>
            <a-popconfirm content="您确定要删除吗?" @ok="doDelete(record)">
              <a-button status="danger">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
<script setup lang="ts">
  import { computed, onMounted, ref, watchEffect } from 'vue';
  import {
    User,
    UserAddRequest,
    UserControllerService,
    UserQueryRequest,
    UserUpdateRequest,
  } from '@/api/generated';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import moment from 'moment/moment';

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const size = ref<SizeProps>('medium');
  const dataList = ref([]);
  const total = ref(0);
  const visible = ref(false);
  const addVisible = ref(false);
  const addForm = ref<FormInstance>();
  const searchParams = ref<UserQueryRequest>({
    userName: '',
    userProfile: '',
    userRole: '',
    pageSize: 6,
    current: 1,
  });
  const formData = ref<UserUpdateRequest>({
    id: 0,
    userName: '',
    userAvatar: '',
    userProfile: '',
    userRole: '',
  });
  const addData = ref<UserAddRequest>({
    userName: undefined,
    userAvatar: undefined,
    userRole: undefined,
    userAccount: undefined,
  });
  const densityList = computed(() => [
    {
      name: '迷你',
      value: 'mini',
    },
    {
      name: '偏小',
      value: 'small',
    },
    {
      name: '中等',
      value: 'medium',
    },
    {
      name: '偏大',
      value: 'large',
    },
  ]);
  const rules = {
    userAccount: [
      {
        required: true,
        message: '账号不能为空',
      },
    ],
  };
  const columns = [
    {
      title: '用户头像',
      slotName: 'userAvatar',
      align: 'center',
    },
    {
      title: 'id',
      dataIndex: 'id',
      align: 'center',
    },
    {
      title: '账号',
      dataIndex: 'userAccount',
      align: 'center',
    },
    {
      title: '用户昵称',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '用户简介',
      slotName: 'userProfile',
      align: 'center',
    },
    {
      title: '用户角色',
      slotName: 'userRole',
      align: 'center',
    },
    {
      title: '创建时间',
      slotName: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      slotName: 'optional',
      align: 'center',
    },
  ];
  const loadData = async () => {
    const res = await UserControllerService.listUserByPageUsingPost(
      searchParams.value
    );
    if (res) {
      dataList.value = res.records;
      total.value = res.total;
    } else {
      Message.error(`加载失败，${res.message}`);
    }
  };
  /**
   * 监听 searchParams 变量，改变时触发页面的重新加载
   */
  watchEffect(() => {
    loadData();
  });

  /**
   * 页面加载时，请求数据
   */
  onMounted(() => {
    loadData();
  });
  /**
   * 选择表格密度
   */
  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
  ) => {
    size.value = val as SizeProps;
  };
  /**
   * 搜索
   */
  const search = () => {
    // 这里需要重置搜索页号
    searchParams.value = {
      ...searchParams.value,
      current: 1,
    };
  };
  /**
   * 切换页码
   * @param page
   */
  const onPageChange = (page: number) => {
    searchParams.value = {
      ...searchParams.value,
      current: page,
    };
  };
  /**
   * 打开修改窗口
   * @param user
   */
  const handleClick = (user: User) => {
    formData.value = JSON.parse(JSON.stringify(user));
    visible.value = true;
  };

  /**
   * 新增
   */
  const doInsert = async () => {
    const res = await UserControllerService.addUserUsingPost(addData.value);
    if (res) {
      Message.success('新增成功');
      addVisible.value = false;
      loadData();
    } else {
      Message.error(`新增失败，${res.message}`);
    }
  };
  /**
   * 删除
   * @param user
   */
  const doDelete = async (user: User) => {
    const res = await UserControllerService.deleteUserUsingPost({
      id: user.id,
    });
    if (res) {
      Message.success('删除成功');
      loadData();
    } else {
      Message.error('删除失败');
    }
  };
  /**
   * 更新
   */
  const doUpdate = async () => {
    const res = await UserControllerService.updateUserUsingPost(formData.value);
    if (res) {
      Message.success('更新成功');
      loadData();
    } else {
      Message.error(`更新失败，${res.message}`);
    }
  };
  const handleCancel = () => {
    visible.value = false;
  };
</script>

<style scoped lang="less">
  .container {
    padding: 20px;
  }
</style>
